package com.jdy.haoduoaiteacher.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.BannerAdapter.OnBannerClickListener;
import com.jdy.haoduoaiteacher.adapter.CategoryGridViewAdapter.OnGridItemClickListener;
import com.jdy.haoduoaiteacher.adapter.DubStoryListAdapter;
import com.jdy.haoduoaiteacher.enums.MediaType;
import com.jdy.haoduoaiteacher.enums.PlayState;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.intface.IMParseListener;
import com.jdy.haoduoaiteacher.model.CarlaClassicVo;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.LeBanner;
import com.jdy.haoduoaiteacher.model.LeHotRecomStory;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.StoryCollectionItem;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ImageLoader;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.OnDataReceivedListener;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.HorizontalIndicator;
import com.jdy.haoduoaiteacher.view.visualizer.FrequencyDistributionBarView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoaiteacher.R;

//import com.jdy.haoduoaiteacher.util.ImHelper;
//import com.tencent.TIMConnListener;
//import com.tencent.TIMManager;

/**
 * 讲故事 唱儿歌
 * 
 * @author hf
 * 
 */

public class TabTellStoryActivity extends BaseActivity implements
    OnGridItemClickListener, OnBannerClickListener, OnScrollListener,
    OnClickListener, OnRefreshListener, IMParseListener, OnDataReceivedListener {

  private static final String TAG = TabTellStoryActivity.class.getSimpleName();

  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.device_stateview, click = true)
  private FrequencyDistributionBarView device_stateview;
  @InjectView(id = R.id.img_back, click = true)
  private View img_back;
  @InjectView(id = R.id.tv_editbox, click = true)
  private View tv_editbox;

  private String xml = "";

  private LeUser mLeUser;

  private ArrayList<LeHotRecomStory> mRecommendStroyList = null;

  private ArrayList<CartoonVo> mBookStoryList = null;

  private ArrayList<StoryCollectionItem> storyCollectionList = null;

  @InjectView(id = R.id.dub_recommand_story_layout)
  private View recommendView;

  @InjectView(id = R.id.dub_book_story_layout)
  private View bookView;

  @InjectView(id = R.id.dub_story_catalog_listview)
  private com.jdy.haoduoaiteacher.view.ListViewForScrollView dubCatelogListview;

  private LinearLayout mRecommendRootLayout;

  private LinearLayout mBookRootLayout;

  private ImageView mRecommendIconImg;

  private ImageView mBookIconImg;

  private TextView recommendTv;

  private TextView bookTv;

  private ImageView recommendMoreImg;

  private ImageView bookMoreImg;

  private DubStoryListAdapter dubStoryListAdapter;

  private HorizontalScrollView mRecommendHSV;

  private HorizontalIndicator mRecommendHI;

  private HorizontalScrollView mBookHSV;

  private HorizontalIndicator mBookHI;
//
//  private ImHelper mImHelper;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.tab_tellstory_fragment);

    hideTitleView();
    bindService();
    initialize();
    initView();
    initListener();
    loadData();

//    TIMManager.getInstance().setConnectionListener(new TIMConnListener() {
//
//      @Override
//      public void onWifiNeedAuth(String arg0) {
//        // TODO Auto-generated method stub
//
//      }
//
//      @Override
//      public void onDisconnected(int arg0, String arg1) {
//        LeConfig.isDeviceConnect = false;
//
//        if (device_stateview != null) {
//          device_stateview.setPlaying(false);
//        }
//      }
//
//      @Override
//      public void onConnected() {
//        // TODO Auto-generated method stub
//
//      }
//    });
  }

  private void bindService() {

//    mImHelper = MyTeacherApp.getInstance().getImHelper();
//    if (mImHelper != null && mImHelper.isLogin()) {
//      mImHelper.setOnDataReceivedListener(this);
//      mImHelper.setIMParseListener(this);
//
//      try {
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("code", "app");
//        dataJson.put("act", "machineinfo");
//        mImHelper.send(dataJson.toString());
//      } catch (JSONException e) {
//        e.printStackTrace();
//      } catch (Exception e) {
//        e.printStackTrace();
//      }
//    }

  }

  private void initView() {
    tv_editbox.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    mRecommendRootLayout = (LinearLayout) recommendView
        .findViewById(R.id.h_layout);
    recommendTv = (TextView) recommendView.findViewById(R.id.catelog_title_tv);
    mRecommendIconImg = (ImageView) recommendView.findViewById(R.id.icon_img);
    mRecommendIconImg.setVisibility(View.GONE);
    recommendTv.setText("热门推荐");
    recommendMoreImg = (ImageView) recommendView.findViewById(R.id.more_img);
    mRecommendHSV = (HorizontalScrollView) recommendView
        .findViewById(R.id.h_scrollview);
    mRecommendHI = (HorizontalIndicator) recommendView
        .findViewById(R.id.h_indicator);

    mBookHSV = (HorizontalScrollView) bookView.findViewById(R.id.h_scrollview);
    mBookHI = (HorizontalIndicator) bookView.findViewById(R.id.h_indicator);
    mBookHSV.getViewTreeObserver().addOnScrollChangedListener(
        new OnScrollChangedListener() {
          @Override
          public void onScrollChanged() {
            int deltaX = mBookHSV.getScrollX();
            DisplayMetrics metrics = getResources().getDisplayMetrics();
            int maxX = mBookHSV.getChildAt(0).getMeasuredWidth()
                - metrics.widthPixels + 5;
            mBookHI.onScrollChanged(deltaX, maxX);
          }
        });

    recommendMoreImg.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(TabTellStoryActivity.this, PrivateStoryActivity.class);
        intent.putExtra("titles", "热门推荐");
        startActivity(intent);
      }
    });

    mBookIconImg = (ImageView) bookView.findViewById(R.id.icon_img);
    mBookIconImg.setVisibility(View.GONE);
    bookTv = (TextView) bookView.findViewById(R.id.catelog_title_tv);
    bookTv.setText("绘本故事");
    bookMoreImg = (ImageView) bookView.findViewById(R.id.more_img);
    bookMoreImg.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        // Intent intent = new Intent();
        // intent.setClass(TabTellStoryActivity.this,
        // IllustratedStoryActivity.class);
        // startActivity(intent);
      }
    });

    mBookRootLayout = (LinearLayout) bookView.findViewById(R.id.h_layout);
  }

  private CarlaClassicVo convert2CarlaClassicVo(LeHotRecomStory recommendStroy) {

    if (recommendStroy == null)
      return null;
    LeHotRecomStory lhr = recommendStroy;
    CarlaClassicVo ccv = new CarlaClassicVo();
    ccv.id = lhr.id; // );
    ccv.category_id = lhr.category_id; // );
    ccv.catalog = lhr.catalog; // );
    ccv.name = lhr.name; // );
    ccv.cover = lhr.cover;// );
    ccv.url = lhr.url;// );
    ccv.enabled = lhr.enabled; // );
    ccv.sort = lhr.sort; // );
    ccv.length = lhr.length; // );
    ccv.agefrom = 0; // );
    ccv.ageto = 0;
    ccv.lines = lhr.lines; // );
    ccv.created_at = lhr.created_at; // );
    ccv.updated_at = lhr.updated_at; // );
    ccv.deleted_at = lhr.deleted_at; // );
    ccv.followers = lhr.followers;// );
    ccv.corner_icon = lhr.corner_icon; // );
    ccv.author = lhr.author; // );
    ccv.tags = lhr.tags; // );
    return ccv;
  }

  private ImageLoader mImageLoader;

  private void setRecommendStoryView(List<LeHotRecomStory> rList) {
    int i = 0;
    int size = rList.size();
    for (; i < size; i++) {
      final LeHotRecomStory lhr = rList.get(i);
      View hChild = LayoutInflater.from(this).inflate(
          R.layout.horizontallist_item, null);
      final ImageView coverImg = (ImageView) hChild.findViewById(R.id.img);
      ImageView playStateImg = (ImageView) hChild
          .findViewById(R.id.play_state_img);
      playStateImg.setVisibility(View.GONE);
      coverImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

//          Intent recode = new Intent();
//
//          Bundle bundle = new Bundle();
//
//          bundle.putSerializable("carlaclassic", convert2CarlaClassicVo(lhr));
//
//          recode.putExtras(bundle);
//
//          recode.setClass(TabTellStoryActivity.this, RecordActivity.class);
//
//          startActivity(recode);
        }
      });
      coverImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

      TextView titleTv = (TextView) hChild.findViewById(R.id.tittle);

      titleTv.setText(lhr.name);

      if (Tools.isNotEmpty(lhr.cover))
        Picasso.with(this).load(lhr.cover).fit().centerCrop()
            .placeholder(getResources().getDrawable(R.drawable.default_cover))
            .error(getResources().getDrawable(R.drawable.default_cover))
            .into(coverImg, new Callback() {

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onError() {
                if (mImageLoader == null) {
                  mImageLoader = new ImageLoader(TabTellStoryActivity.this);
                }
                mImageLoader.DisplayImage(lhr.cover, coverImg, false);

              }
            });

      LayoutParams params_image = new LayoutParams(
          LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

      params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
          Tools.getPixelByDip(this, 5), 0);

      hChild.setLayoutParams(params_image);

      mRecommendRootLayout.addView(hChild);
    }
  }

  private void setBookStoryView(List<CartoonVo> bookList) {
    if (Tools.isEmpty(bookList) || bookList.isEmpty()) {
      return;
    }

    int i = 0;
    int size = bookList.size();
    for (; i < size; i++) {
      final CartoonVo cv = bookList.get(i);
      View hChild = LayoutInflater.from(this).inflate(R.layout.illustsotryitem,
          null);

      final ImageView coverImg = (ImageView) hChild.findViewById(R.id.cover);

      TextView titleTv = (TextView) hChild.findViewById(R.id.title);

      coverImg.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

          // Intent intent = new Intent(TabTellStoryActivity.this,
          // StoryBookActivity.class);
          // Bundle bundle = new Bundle();
          // bundle.putSerializable("illustratedstory", cv);
          // intent.putExtras(bundle);
          // startActivity(intent);
        }
      });

      coverImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

      titleTv.setText(cv.name);

      if (Tools.isNotEmpty(cv.cover))
        Picasso.with(this).load(cv.cover).fit().centerCrop()
            .placeholder(getResources().getDrawable(R.drawable.default_cover))
            .error(getResources().getDrawable(R.drawable.default_cover))
            .into(coverImg, new Callback() {

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onError() {
                if (mImageLoader == null) {
                  mImageLoader = new ImageLoader(TabTellStoryActivity.this);
                }
                mImageLoader.DisplayImage(cv.cover, coverImg, false);

              }
            });

      float ratio = Tools.getPixelRatio(this);
      int fixedWidth = (int) (ratio * 280);
      LayoutParams params_image = new LayoutParams(
          fixedWidth, LayoutParams.WRAP_CONTENT);
      params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
          Tools.getPixelByDip(this, 5), 0);
      hChild.setLayoutParams(params_image);
      mBookRootLayout.addView(hChild);
    }
  }

  private void setCollectionStoryView(ArrayList<StoryCollectionItem> sciList) {
    if (dubStoryListAdapter == null) {
      dubStoryListAdapter = new DubStoryListAdapter(this, sciList);
      dubCatelogListview.setAdapter(dubStoryListAdapter);
    } else {
      dubStoryListAdapter.notifyDataSetChanged();
    }
  }

  private void loadData() {
    loadRecommendStory();
    // loadBookStory();
    loadCollectionStory();
  }

  private void loadRecommendStory() {

    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (mRecommendStroyList != null) {
            mRecommendStroyList.clear();
          }

          if (Tools.isNotEmpty(result.data)) {
            mRecommendStroyList = (ArrayList<LeHotRecomStory>) JsonSerializer
                .getInstance().deserialize(result.data, ArrayList.class,
                    LeHotRecomStory.class);
            setRecommendStoryView(mRecommendStroyList);

            mRecommendHSV.getViewTreeObserver().addOnScrollChangedListener(
                new OnScrollChangedListener() {
                  @Override
                  public void onScrollChanged() {
                    int deltaX = mRecommendHSV.getScrollX();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    if (mRecommendHSV.getChildAt(0).getMeasuredWidth() < metrics.widthPixels) {
                      mRecommendHI.setVisibility(View.GONE);
                      return;
                    } else {
                      mRecommendHI.setVisibility(View.VISIBLE);
                    }

                    int maxX = mRecommendHSV.getChildAt(0).getMeasuredWidth()
                        - metrics.widthPixels + 5;
                    mRecommendHI.onScrollChanged(deltaX, maxX);
                  }
                });
          }
        }

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("size", 6);

        return HttpUtils.startRequest(HttpUtils.HOST_API
            + "/api/2.0/catalog/story/recommand", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void loadBookStory() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          try {
            JSONObject json = new JSONObject(result.data);
            String data = json.optString("data");
            JSONArray array = new JSONArray(data);
            if (mBookStoryList != null) {
              mBookStoryList.clear();
            }
            for (int i = 0; i < array.length(); i++) {
              JSONObject obj = ((JSONObject) array.opt(i));

              if (Tools.isNotEmpty(obj.toString())) {
                CartoonVo itemVo = JsonSerializer.getInstance().deserialize(
                    obj.toString(), CartoonVo.class);
                mBookStoryList.add(itemVo);
              }
            }
            setBookStoryView(mBookStoryList);
          } catch (Exception e) {
            // TODO
          }
        } else {
          toastShow(result.data);

          pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
          pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
        }

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("catalog", "dub");
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.GET_CATALOG_ALBUM, param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void loadCollectionStory() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (storyCollectionList.size() > 0)
            storyCollectionList.clear();
          try {

            storyCollectionList = (ArrayList<StoryCollectionItem>) JsonSerializer
                .getInstance().deserialize(result.data, ArrayList.class,
                    StoryCollectionItem.class);

            ArrayList<StoryCollectionItem> filtered = new ArrayList<StoryCollectionItem>();
            for (StoryCollectionItem item : storyCollectionList) {
              if (Tools.isNotEmpty(item.getStory_collection()))
                filtered.add(item);
            }

            setCollectionStoryView(filtered);
          } catch (Exception e) {

          }
        } else {
          toastShow(result.data);

          pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
          pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + "/api/2.0/catalog/story/collection", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void initialize() {
    mLeUser = MyTeacherApp.getInstance().getUserTeacher();
    mBookStoryList = new ArrayList<>();
    storyCollectionList = new ArrayList<>();
    // mLeUser = MyTeacherApp.getInstance().getUser();
  }

  private void initListener() {
    pullToRefreshLayout.setOnRefreshListener(this);
    // listview.setLoadMore(false);
  }

  @Override
  public void onClick(View v) {

    switch (v.getId()) {
    case R.id.tv_editbox:
      if (LeConfig.isLogin) {
        Intent toSearch = new Intent(this, SearchActivity.class);
        toSearch.putExtra("type", "story");
        startActivity(toSearch);
      } else {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
      }

      break;
    case R.id.device_stateview:
      Intent intent = new Intent();
      if (LeConfig.isLogin) {
      //  intent.setClass(this, DevicePropertyActivity.class);
      } else {
        intent.setClass(this, LoginActivity.class);
      }

      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);

      break;
    case R.id.img_back:
      this.finish();
      break;

    default:
      break;
    }

  }

  @Override
  public void onResume() {
    super.onResume();

    if (!LeConfig.isDeviceConnect) {
      if (device_stateview != null) {
        device_stateview.setPlaying(false);
      }
    }

    MobclickAgent.onPageStart(TAG);
  }

  @Override
  public void onPause() {
    super.onPause();
    MobclickAgent.onPageEnd(TAG);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

//    if (mImHelper != null) {
//      mImHelper.removeDataReceivedListener(this);
//      mImHelper.removeIMParseListener(this);
//    }
  }

  @Override
  public void onGridItemClik(int pos) {

  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {

  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {

  }

  /*
   * 下拉刷新
   */
  // private class GetDataTask extends AsyncTask<Void, Void, String> {
  //
  // @Override
  // protected String doInBackground(Void... params) {
  // // HttpClient httpClient = new DefaultHttpClient();
  // // HttpGet request = new HttpGet("");
  // // HttpConnectionParams.setConnectionTimeout(request.getParams(), 10 *
  // // 1000);
  // // HttpConnectionParams.setSoTimeout(request.getParams(), 10 * 1000);
  // // HttpConnectionParams.setTcpNoDelay(request.getParams(), true);
  // // try {
  // // xml = httpClient.execute(request, new BasicResponseHandler());
  // // } catch (ClientProtocolException e) {
  // // e.printStackTrace();
  // // } catch (IOException e) {
  // // e.printStackTrace();
  // // }
  // // loadBookStory();
  // // loadCarlaClassic();
  // xml = "test";
  // return xml;
  // }
  //
  // @Override
  // protected void onPostExecute(String result) {
  // super.onPostExecute(result);
  // }
  // }

  @Override
  public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
    // new GetDataTask().execute();
    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
  }

  @Override
  public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

  }

  @Override
  public void onBannerClicked(LeBanner banner) {

  }

  @Override
  public void onRemoteLogin() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (device_stateview != null) {
          device_stateview.setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onConnectionChanged(boolean connect) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          JSONObject data) {

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub
        if (playState.equals(PlayState.Playing)) {
          device_stateview.setPlaying(true);
        } else {
          device_stateview.setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onDataReceived(String data) {
    if (Tools.isNotEmpty(data)) {
      try {
        JSONObject jsonData = new JSONObject(data.toString());
        if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")) {
          if (jsonData.getString("act").contains(
              "Device_APP_Connection_Switched")) {
            // Intent logoutIntent = new Intent(
            // "com.jdy.haoduoaiteacher.activity.logout");
            // sendBroadcast(logoutIntent);
            //
            // LeConfig.isLogin = false;
            // LeConfig.isDeviceActivated = false;
            // LeConfig.isDeviceBinded = false;
            // LeConfig.isInfoFilled = false;
            // LeConfig.isDeviceConnect = false;
            //
            // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
            // getApplicationContext()).setTitle("下线通知")
            // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
            // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            //
            // @Override
            // public void onClick(DialogInterface dialog, int which) {
            // dialog.dismiss();
            // }
            // });
            // final CustomOneBtnDialog cd = cdb.create();
            // cd.getWindow()
            // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            // cd.setOnDismissListener(new OnDismissListener() {
            //
            // @Override
            // public void onDismiss(DialogInterface dialog) {
            // Intent toActivityIntent = new Intent(TabTellStoryActivity.this,
            // LoginActivity.class);
            // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
            // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(toActivityIntent);
            // finish();
            // }
            // });
            // cd.show();
          }
        }
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

  }

  @Override
  public void onNetWorkDisconn() {
    if (device_stateview != null) {
      device_stateview.setPlaying(false);
    }

  }

}
